package com.baoming.web.action;

import com.baoming.container.ServiceContainer;
import com.baoming.domain.Member;
import com.baoming.service.IMemberService;
import com.baoming.tool.MemberTool;
import com.baoming.util.Struts2UploadUtil;
import com.baoming.util.UploadUtil;
import com.opensymphony.xwork2.ModelDriven;
 

@SuppressWarnings("serial")
public class MemberAction extends BaseAction implements ModelDriven<Member>{
	
	private Member member = new Member() ; 
	private IMemberService memberService = (IMemberService) ServiceContainer.getService(IMemberService.SERVICE) ; 

	/**
	 * 用户修改密码
	 */
	public String pwd(){
		//得到旧密码 如果为空 则直接返回密码修改页面
		String old = request.getParameter("oldpwd") ;
		if(old == null || "".equals(old)){
			return SUCCESS ; 
		}
		
		//得到当前用户信息
		Member currentMember = MemberTool.getGlobalMember(request) ; 
		
		//与旧密码验证
		if(currentMember.getPassword().equals(old.trim())){
			String newPwd = request.getParameter("newpwd") ; 
			memberService.updateMemberPwd(newPwd , currentMember.getId()) ; 
			//返回界面 让用户重新登陆 
			return "login" ; 
		}else{
			//返回错误代码  1为旧密码不正确  
			request.setAttribute("error", "1") ; 
			return SUCCESS ; 
		}
		  
	}
	
	/**
	 * 修改用户信息
	 * @return
	 */
	public String update(){
		
		//数据库查询得到修改的用户信息
		String memberId = MemberTool.getGlobalMemberId(request) ; 
		
		/*
		 * 图像处理
		 */
		Member modifyMember = new Member() ; 
		if(Struts2UploadUtil.fileUtil(member.getPic())){
			String picPath = UploadUtil.uploadSimpleFile(member.getPic(), member.getPicFileName(), "upload") ;  
			modifyMember.setPicPath(picPath) ; 
			
			Member member = MemberTool.getGlobalMember(request) ; 
			member.setPicPath(picPath) ; 
			
		}else{
			modifyMember.setPicPath(null) ; 
		}
	   
		modifyMember.setId(memberId) ; 
		modifyMember.setName(member.getName()) ;  
		modifyMember.setPhone(member.getPhone()) ; 
		modifyMember.setQq(member.getQq()) ; 
		modifyMember.setAddress(member.getAddress()) ; 
		modifyMember.setBirthday(member.getBirthday()) ; 
		
		//更新用户基本信息
		memberService.updateMemberMsg(modifyMember) ;
		
		//得到修改用户的信息
		profile() ; 
		
		return "modify" ; 
	}
	
	/**
	 * 用户账号
	 * @return
	 */
	public String profile(){
		
		//数据库查询得到修改的用户信息
		String memberId = MemberTool.getGlobalMemberId(request) ; 
		Member modifyMember = memberService.selectMember(memberId) ; 
		request.setAttribute("member", modifyMember) ; 
		
		return SUCCESS; 
	}
	
	/**
	 * 保存用户
	 */
	@Override
	public String add() {
		
		return null;
	}

	@Override
	public String edit() {
		return SUCCESS ;
	}

	@Override
	public String manager() {
		return null;
	}

	@Override
	public String remove() {
		return null;
	}

	@Override
	public String removeGroup() {
		return null;
	}

	public Member getModel() {
		return member ;
	}

}
